package com.powernode.config;

import cn.hutool.core.util.ObjectUtil;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName FeignInterceptor
 * @Description Feign拦截器
 * @Date 2024/07/21 17:05
 */
@Component
@Slf4j
public class FeignInterceptor implements RequestInterceptor {

    /**
     * 永不失效token
     */
    @Value("{token.feign}")
    private String token;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNull(requestAttributes)) {
            log.error("FeignInterceptor: requestAttributes is null");
            // 设置默认authorization
            requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.AUTHORIZATION_PREFIX + token);
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        if (ObjectUtil.isNull(request)) {
            log.error("FeignInterceptor: request is null");
            // 设置默认authorization
            requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.AUTHORIZATION_PREFIX + token);
            return;
        }
        // 获取authorization（即token）
        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
        requestTemplate.header(AuthConstants.AUTHORIZATION, authorization);
    }
}
